package org.zjx.prop.repository.impl;

import org.zjx.prop.db.ItemInstanceDB;
import org.zjx.prop.domain.model.ItemInstance;
import org.zjx.prop.repository.ItemInstanceRepository;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

public class ItemInstanceRepositoryImpl implements ItemInstanceRepository {
    private final ItemInstanceDB itemInstanceDB;

    public ItemInstanceRepositoryImpl(ItemInstanceDB itemInstanceDB) {
        this.itemInstanceDB = itemInstanceDB;
    }

    @Override
    public Optional<ItemInstance> findById(int instanceId) {
        return Optional.ofNullable(itemInstanceDB.findById(instanceId));
    }

    @Override
    public List<ItemInstance> findByPlayerId(String playerId) {
        return itemInstanceDB.findByPlayerId(playerId);
    }

    @Override
    public List<ItemInstance> findAllById(List<Integer> instanceIds) {
        return instanceIds.stream()
                .map(itemInstanceDB::findById)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    @Override
    public ItemInstance save(ItemInstance instance) {
        if (itemInstanceDB.findById(instance.getId()) != null) {
            itemInstanceDB.update(instance);
        } else {
            itemInstanceDB.insert(instance);
        }
        return instance;
    }

    @Override
    public boolean update(List<ItemInstance> itemInstances) {
        itemInstances.forEach(this::save);
        return true;
    }

    @Override
    public void delete(int instanceId) {
        itemInstanceDB.delete(instanceId);
    }
}